import assets from './assets.json';
import abi from './abi.json'

let tronWeb = window.tronWeb
var platformAddress = "TNp5bgJcfw2Eduqdt78ccz7MR1LmyfJH9r"

let i = setInterval(() => {
    if ((typeof window.tronWeb) !== 'undefined') {
        tronWeb = window.tronWeb
        clearInterval(i)
    }
}, 1000);


export function version() {
    return tronWeb.version
}

export async function identity() {
    if (tronWeb !== 'undefined') {
        return tronWeb.defaultAddress.base58;
    }
    return false;
}

// 充值TRC20代币
export async function recharge(token, amount) {
    if (token.toUpperCase() === "TRX") {
        return await rechargeTrx(amount);
    }
    let tokenContract = await tronWeb.contract(abi,assets[token])
    let decimals = await tokenContract.decimals().call();
    // let userBalance = await tokenContract.balanceOf(tronWeb.defaultAddress.hex).call();
    amount = tronWeb.toHex(amount * (10 ** decimals));
    // todo BigInteger
    // if (userBalance < amount) {
    //     return false;
    // }
    return await tokenContract.transfer(platformAddress, amount).send((res)=>{
       return res 
    }).catch((e) => {
        return e
    });
}

// 充值Trx
export async function rechargeTrx(amount) {  
    let userBalance = await tronWeb.trx.getBalance()
    userBalance = tronWeb.fromSun(userBalance); 
    amount = tronWeb.toHex(amount * (10 ** 6));
    if (userBalance < amount) {
        return false;
    }
    return await tronWeb.trx.sendTransaction(platformAddress, amount);
}


//钱包代币余额查询
export async function tokenBalance(token = '') {

    if (token.toUpperCase() === "TRX") {
        let userBalance = await tronWeb.trx.getBalance()
        return tronWeb.fromSun(userBalance);
    } else {
        let tokenContract = await tronWeb.contract(abi,assets[token])
        let decimals = await tokenContract.decimals().call();
        let userBalance = await tokenContract.balanceOf(tronWeb.defaultAddress.hex).call();
        let b;
        if (typeof userBalance.balance != "undefined") {
            b = userBalance.balance._hex;
        } else {
            b = userBalance._hex;
        }
        return b / (10 ** decimals);
    }
}


// {"name":"DOSBTC","decimals":8,"contract":"TcKTZypbmZRLmBHTamYZwdngT7YHcGbMuH9","currency":"DOS
//   _TOKEN"}
export async function tokenInfo(token = '') {
    if (token.toUpperCase() === "TRX") {
        return {
            "name": "TRX",
            "decimals": 6,
            "contract": '',
            "currency": 'trx'
        }
    }
    let tokenContract = await tronWeb.contract().at(assets[token])
    let decimals = await tokenContract.decimals().call();
    let name = await tokenContract.name().call();
    let symbol = await tokenContract.symbol().call();
    return {
        "name": name,
        "decimals": decimals,
        "contract": assets[token],
        "currency": symbol
    }
}

export async function getTransInfo(tx) {
    return await tronWeb.trx.getTransaction(tx).catch(console.log);
}

export async function getAbi(contract) {
    let instance = await tronWeb.trx.getContract(contract);
    // return instance['abi']['entrys']; 列表
    return instance['abi'];
}
export async function getlimit(){
    let tokenContract = await tronWeb.contract().at(assets["TROT"])
    let limit = await tokenContract.campaignLimit().call()
    return limit
}
export async function getABI(){
    let tokenContract = await tronWeb.contract(abi,assets["TROT"])
    let decimals = await tokenContract.decimals().call();

    let t = await tokenContract.earlyIndex().call();
    
    let t1 = await tokenContract.prizeList(t).call();

    let t2= await tokenContract.campaignCurrent().call();
    let qh=await tokenContract.issue().call();
    let win=tronWeb.address.fromHex(t1.receiver)
    let fhc=await tokenContract.divPool().call()/(10 ** decimals);

    let sc=await tokenContract.drawInterval().call();

    let endTime = await tokenContract.lastRefreshTime().call();
    let fxzl = await tokenContract.totalSupply().call()/(10 ** decimals);
    let dqltl=await tokenContract.balanceOf(assets["TROT"]).call()
    let b;
    if (typeof dqltl.balance != "undefined") {
        b = dqltl.balance._hex;
    } else {
        b = dqltl._hex;
    }
    let dqltls= b / (10 ** decimals)
    let ltl=fxzl-dqltls
    
    let jiangchi = await tokenContract.ewardPool().call()/(10 ** decimals);
    let ranshaolv = await tokenContract.burnProp().call();
    let ranshao = 100000000-fxzl
    let nowtime=await tokenContract.getNow().call();
    let txjj=jiangchi*0.2

    return {
    't1':t1,
    "t2":t2,
    "qh":qh, 
    "endTime":endTime,
    "fhc":fhc ,
    "fxzl":fxzl,
    "dqltl":ltl,
    "jiangchi":jiangchi,
     "ranshao":ranshao,
     "ranshaolv":ranshaolv,
     "nowtime":nowtime,
     "txjj":txjj,
     "sc":sc,
     "win":win
    }

}
export async function getjyrs(){
    let tokenContract = await tronWeb.contract(abi,assets["TROT"])
    let decimals=6
    let fxzl = await tokenContract.totalSupply().call()/(10 ** decimals);
    let ranshao = 100000000-fxzl
    let ranshaolv = await tokenContract.burnProp().call();
    return {
        "fxzl":fxzl,
        "ranshao":ranshao,
        "ranshaolv":ranshaolv
    };
}

export async function  getcbfh (){
    let tokenContract = await tronWeb.contract(abi,assets["TROT"])
    let decimals=6
    let fhc=await tokenContract.divPool().call()/(10 ** decimals);
    return {"fhc":fhc};
}


export async function getwdby(){
    let tokenContract = await tronWeb.contract(abi,assets["TROT"])
    let decimals=6
    let jiangchi = await tokenContract.ewardPool().call()/(10 ** decimals);
    let t2= await tokenContract.gameFiled().call();
    let qh=t2.issue;
    let t = t2.earlyIndex;
    let endTime = t2.lastRefreshTime;
    let nowTime=await tokenContract.getNow().call();
    let sc=await tokenContract.drawInterval().call();
    let t1 = await tokenContract.prizeList(t).call();
    let win=tronWeb.address.fromHex(t1.receiver)
    return {"jiangchi":jiangchi,"qh":qh,   "sc":sc, "t2":t2.campaignCurrent, "endTime":endTime,  "nowtime":nowTime, "win":win};
}


export async function getABIs(t){    
    let tokenContract = await tronWeb.contract(abi,assets["TROT"])
    let t1 = await tokenContract.prizeList(t).call();
    let ts=tronWeb.address.fromHex(t1.receiver)
    return ts;
}
export async function getSign(i){
    let to =await tronWeb.sha3(i)
    let sing=await tronWeb.trx.sign(to)
    return sing
}